package com.zl.util
{
	import cn.skyclass.controls.AdvancedAlert;
	
	import mx.collections.ArrayCollection;
	import mx.controls.DataGrid;
	import mx.controls.dataGridClasses.DataGridColumn;

	public class MeasureUtil
	{
		public function MeasureUtil()
		{
		}
		
		/**
		 * 解析导入的Excel
		 * dg原始数据表格
		 * itemCount零件数，operatorCount检测员人数，measureCount每个检测员记录数据次数
		 */
		public static function parseExcelData(dg:DataGrid):Object{
			if(!dg){
				AdvancedAlert.info('无数据，无法进行分析！ ');
				return null;
			}
			var columns:Array = dg.columns;
			var dataSource:ArrayCollection = dg.dataProvider as ArrayCollection;
			//Exvel表格中列数<=1,或者行数=0，说明无有效测量数据
			if(!columns || columns.length<=1 ||
				!dataSource || dataSource.length==0){
				AdvancedAlert.info('无数据，无法进行分析！ ');
				return null;
			}
			
			var itemCount:uint = dataSource.length;//零件数
			var operatorCount:uint = 0;//检测员人数
			var lastMeasureCount:uint = 0;//上一位检测员的检测次数 
			var measureCount:uint = 0;//每位检测员的测量次数 
			
			var colLength:uint = columns.length;
			for(var i:uint=1; i<colLength; i++){
				var column:DataGridColumn = columns[i] as DataGridColumn;
				if(column.headerText != ' ') {
					operatorCount++;
					if(!isMeasureCountEqual(measureCount, lastMeasureCount, true)){
						AdvancedAlert.info('检测员记录数据次数不一致！\n请调整模板数据，重新上传！ ');
						return null;
					}
					lastMeasureCount = measureCount;
					measureCount = 0;
				}
				measureCount++;
				if(!isMeasureCountEqual(measureCount, lastMeasureCount, false)){
					AdvancedAlert.info('检测员记录数据次数不一致！\n请调整模板数据，重新上传！ ');
					return null;
				}
			}
			if(!isMeasureCountEqual(measureCount, lastMeasureCount, true)){
				AdvancedAlert.info('检测员记录数据次数不一致！\n请调整模板数据，重新上传！ ');
				return null;
			}
			
			if(measureCount!=2 && measureCount!=3){
				AdvancedAlert.info('本系统暂只支持重复检测2次或3次的情况！\n请调整模板数据，重新上传！ ');
				return null;
			}
			if(operatorCount<=1 || operatorCount>15){
				AdvancedAlert.info('本系统暂只支持2~15个检测员的情况！\n请调整模板数据，重新上传！ ');
				return null;
			}
			if(itemCount<=1 || itemCount>15){
				AdvancedAlert.info('本系统暂只支持2~15个零件的情况！\n请调整模板数据，重新上传！ ');
				return null;
			}
			
			return {itemCount:itemCount, operatorCount:operatorCount, measureCount:measureCount};
			
			function isMeasureCountEqual(count:uint, lastCount:uint, newStart:Boolean):Boolean{
				if(lastCount==0) return true;//第1列数据，不作比较
				if(newStart) return (count==lastCount);//开始分析下一位检测员数据
				if(count<=lastCount) return true;//当前检测员记录数据次数未超过前一位检测员，继续分析
				return false;
			}
		}
		
		/**
		 * 通过Excel原始数据，计算均值、极差
		 * dg原始数据表格
		 * itemCount零件数，operatorCount检测员人数，measureCount每个检测员记录数据次数
		 */
		public static function calcAvgAndR(dg:DataGrid,
										   itemCount:uint, operatorCount:uint, measureCount:uint):Object{
			var origColumns:Array = dg.columns;
			var origDataSource:ArrayCollection = dg.dataProvider as ArrayCollection;
			
			var operatorNames:Array = [];//操作员姓名列表
			for(var i:uint=0; i<operatorCount; i++){
				var operatorIndex:uint = i*measureCount+1;//原始数据表格中，显示操作员姓名的列序号
				var column:DataGridColumn = origColumns[operatorIndex] as DataGridColumn;
				var operatorName:String = column.headerText;//操作员姓名
				operatorNames.push(operatorName);
			}
			
			var columns:Array = [];
			var column:DataGridColumn = new DataGridColumn('零件号');
			column.dataField = 'col0';
			columns.push(column);
			for(var i:uint=0; i<operatorCount; i++){//遍历检测员,生成“均值极差表格”的所有列
				var operatorName:String = operatorNames[i];
				column = new DataGridColumn(operatorName+'的平均值');
				column.dataField = 'col'+(i*2+1);
				column.labelFunction = avgAndRColumnLabelFunction;
				columns.push(column);
				column = new DataGridColumn(operatorName+'的极差');
				column.dataField = 'col'+(i*2+2);
				column.labelFunction = avgAndRColumnLabelFunction;
				columns.push(column);
			}
			
			var dataSource:ArrayCollection = new ArrayCollection();
			for(var i:uint=0; i<itemCount; i++){//遍历零件
				var origItem:Object = origDataSource.getItemAt(i);
				var item:Object = new Object();
				item['col0'] = origItem['col0'];
				for(var j:uint=0; j<operatorCount; j++){//遍历检测员
					item['col'+(j*2+1)] = calcAvg(origItem, j);//计算平均值
					item['col'+(j*2+2)] = calcR(origItem, j);//计算极差
				}
				dataSource.addItem(item);
			}
			
			return {columns:columns, dataSource:dataSource};
			
			function calcAvg(origItem:Object, operatorIndex:uint):Number{
				var avg:Number = 0;
				for(var i:uint=1; i<=measureCount; i++){
					avg += Number(origItem['col'+(operatorIndex*measureCount+i)]);
				}
				avg /= measureCount;
				return avg;
			}
			function calcR(origItem:Object, operatorIndex:uint):Number{
				var numberArray:Array = [];
				//遍历该检测员测量某一零件时，记录的数据
				for(var i:uint=1; i<=measureCount; i++){
					var v:Number = Number(origItem['col'+(operatorIndex*measureCount+i)]);
					numberArray.push(v);
				}
				
				var R:Number = calculateMaxMinR(numberArray);
				return R;
			}
			function avgAndRColumnLabelFunction(item:Object, column:DataGridColumn):String{
				return Number(item[column.dataField]).toFixed(3);
			}
		}
		
		/**
		 * 通过均值、极差，计算最终结果
		 * dgAvgAndR平均值极差表格，itemCount零件数，operatorCount检测员人数，measureCount每个检测员记录数据次数
		 */
		public static function calcResult(dgAvgAndR:DataGrid,
										  itemCount:uint, operatorCount:uint, measureCount:uint):Object{
			var experienceData:Object = getExperienceData(measureCount, operatorCount, itemCount);
			var D1:Number = experienceData.D1;
			var D2:Number = experienceData.D2;
			var k1:Number = experienceData.k1;
			var k2:Number = experienceData.k2;
			var k3:Number = experienceData.k3;
			
			var dataSource:ArrayCollection = dgAvgAndR.dataProvider as ArrayCollection;
			
			var avgOfAvg_operator:Array = [];//A检测所有零件平均值的总均值，B检检测所有零件平均值的总均值...
			var avgOfR_operator:Array = [];//A检测的所有零件的极差平均值，B检测的所有零件的极差平均值...
			var avgOfAvg_item:Array = [];//零件1 所有检测员平均值的平均值，零件2 所有检测员平均值的平均值...
			for(var j:uint=0; j<operatorCount; j++){
				avgOfAvg_operator.push(0);
				avgOfR_operator.push(0);
			}
			
			for(var i:uint=0;i<itemCount;i++){
				avgOfAvg_item.push(0);
				var item:Object = dataSource.getItemAt(i);
				
				for(var j:uint=0; j<operatorCount; j++){
					avgOfAvg_operator[j] += Number(item['col'+(j*measureCount+1)]);
					avgOfR_operator[j] += Number(item['col'+(j*measureCount+2)]);
					avgOfAvg_item[i] += Number(item['col'+(j*measureCount+1)]);
				}
				avgOfAvg_item[i] /= operatorCount;
			}
			for(var j:uint=0; j<operatorCount; j++){
				avgOfAvg_operator[j] /= itemCount;
				avgOfR_operator[j] /= itemCount;
			}
			
			var avg_avgOfR_operator:Number = average(avgOfR_operator);//所有检测员的极差平均值
			var XDIEF:Number = calculateMaxMinR(avgOfAvg_operator);
			var Rp:Number = calculateMaxMinR(avgOfAvg_item);
			
			var UCLR:Number = avg_avgOfR_operator*D1;
			var LCLR:Number = avg_avgOfR_operator*D2;
			for(var i:uint=0;i<itemCount;i++){
				var item:Object = dataSource.getItemAt(i);
				for(var j:uint=0; j<operatorCount; j++){
					var R:Number = Number(item['col'+(j*measureCount+2)]);
					if(R>UCLR) return {right:false, UCLR:UCLR};
				}
			}
			
			var EV:Number = avg_avgOfR_operator*k1;
			var s:Number = (XDIEF*k2)*(XDIEF*k2)-(EV*EV/(itemCount*measureCount));
			var AV:Number = (s>0) ? Math.sqrt(s) : 0;
			var RR:Number = Math.sqrt(EV*EV+AV*AV);
			var PV:Number = Rp*k3;
			var TV:Number = Math.sqrt(RR*RR+PV*PV);
			var EV1:Number = (EV/TV)*100;
			var AV1:Number = (AV/TV)*100;
			var RR1:Number = (RR/TV)*100;
			var PV1:Number = (PV/TV)*100;
			var TV1:Number = 100;
			
			return {right:true, EV:EV, AV:AV, RR:RR, PV:PV, TV:TV, EV1:EV1, AV1:AV1, RR1:RR1, PV1:PV1, TV1:TV1};
		}
		
		/**
		 * 获取查表数据（TODO:添加其它情况）
		 */
		public static function getExperienceData(measureCount:uint, operatorCount:uint, itemCount:uint):Object{
			var D1:Number = 0;
			var D2:Number = 0;
			var d21:Number = 1;
			var d22:Number = 1;
			var d23:Number = 1;
			var k1:Number = 0;
			var k2:Number = 0;
			var k3:Number = 0;
			
			if(measureCount==2){
				D1=3.27;
				D2=0.0;
				
			}else if(measureCount==3){
				D1=2.58;
				D2=0.0;
			}
			
			var measureData:MeasureData = new MeasureData();
			d21 = measureData.getData(measureCount, operatorCount*itemCount);
			d22 = measureData.getData(operatorCount, 1);
			d23 = measureData.getData(itemCount, 1);
			
			
			k1=5.15/d21;
			k2=5.15/d22;
			k3=5.15/d23;
			
			return {D1:D1, D2:D2, d21:d21, d22:d22, d23:d23, k1:k1, k2:k2, k3:k3};
		}
		
		/**
		 * 求平均值
		 */
		public static function average(numberArray:Array):Number{
			if(!numberArray || numberArray.length==0) return 0;
			
			var avg:Number = 0;
			for each(var n:Number in numberArray){
				avg += n;
			}
			avg /= numberArray.length;
			
			return avg;
		}
		
		/**
		 * 计算最大值和最小值的极差
		 */
		public static function calculateMaxMinR(numberArray:Array):Number{
			if(!numberArray || numberArray.length==0) return 0;
			
			var firstNumber:Number = Number(numberArray[0]);
			var max:Number = firstNumber;
			var min:Number = firstNumber;
			for each(var n:Number in numberArray){
				if(n > max) max = n;
				if(n < min) min = n;
			}
			
			var R:Number = max-min;
			return R;
		}
		
	}
}